"use strict"
/// <reference path="../../index.d.ts" />
const Controller = require("egg").Controller
let ObjBase = require("obj-base")
const {sendStat, todayRemaining} = require("../extend/helper")

class ChannelController extends Controller {
	constructor(ctx) {
		super(ctx)
		this.constant = this.config.constant
		this.serverConfig = this.config.serverConfig
		this.Channel = this.app.model.Channel
	}
	async	upsertChannel() {
		this.app.cache.channel = undefined
		this.ctx.validate({
			channel_name: "string", remarks: {
				type: "string",
				allowEmpty: true
			},
			stat: ["0", "1"],
			id: {
				type: "pintstr",
				required: false
			}
		}, this.ctx.request.body)
		await this.Channel.upsert(ObjBase.objFetchKeys(this.ctx.request.body, ["channel_name", "remarks", "stat", "id"]))
		this.ctx.body = sendStat(this.constant.NORMAL)
	}

	async list() {
		let data = await this.app.cache.channel
		this.ctx.body = sendStat(this.constant.NORMAL, data)
	}
	/* 
	全部统计 */
	async countALL() {
		this.ctx.validate({aid: "pintstr"}, this.ctx.query)
		let sequelize = this.app.model
		let t = Date.now()
		let redisKey = `empire_aid_count#${this.ctx.query.aid}`

		let obj = await this.ctx.service.db.getSet(redisKey, {
			noExist: async () => {
				let userCount = await sequelize.query(`SELECT app_channel.id, app_channel.channel_name, SUM(ad_channel_count.adClick) AS allClick, t.allUser
				, t.authUser, t.userApprentice
			FROM app_channel
				LEFT JOIN application_user ON application_user.channel = app_channel.id
				LEFT JOIN ad_channel_count ON application_user.id = ad_channel_count.oid
				LEFT JOIN (
					SELECT countUserInvite.channel, COUNT(countUserInvite.id) AS allUser, SUM(countUserInvite.isAuth) AS authUser
						, SUM(countUserInvite.inviterNum) AS userApprentice
					FROM (
						SELECT application_user.id, application_user.channel
							, IF(application_user.nickname IS NULL, 0, 1) AS isAuth
							, COUNT(empire_user.inviteid) AS inviterNum
						FROM application_user
							LEFT JOIN empire_user ON empire_user.inviteid = application_user.id
						WHERE application_user.aid = :aid
						GROUP BY application_user.id
					) countUserInvite
					GROUP BY countUserInvite.channel
				) t
				ON t.channel = app_channel.id
			WHERE application_user.aid = :aid
			GROUP BY app_channel.id`, {logging: false, type: sequelize.QueryTypes.SELECT, replacements: {aid: this.ctx.query.aid}})
				return userCount
			},
			expire: todayRemaining()
		}
		)
		this.ctx.body = sendStat(this.constant.NORMAL, obj.data)
		this.ctx.logger.warn(`${Date.now() - t} ms`)
	}
	/**
	 * 统计数据
	 * 每个数据, (渠道-aid)==> 日期
	 */
	async countByDate() {
		let query = this.ctx.query
		this.ctx.validate({aid: "pintstr", channelId: "pintstr"}, query)
		let date = await this.service.count.countDateChannel(ObjBase.objFetchKeys(query, ["aid", "channelId"]))
		//  总点击, 总广告曝光
		let unionData = await this.service.count.countUserInviteAdClick({aid: query.aid, channelId: query.channelId})
		let dateLevel = await this.service.count.getDateLevel({aid: query.aid, channelId: query.channelId})
		// console.log(seven)
		let res = ObjBase.arrayKeyConct([unionData, date.d, dateLevel], "dateList", {sort: -1})
		res.forEach((v) => {
			v.allInviteid = v.allInviteid || 0
			v.allClick = v.allClick || 0
			// if (dateLevelMap[v.dateList]) {
			v.diff1 = v.diff1 || 0
			v.diff3 = v.diff3 || 0
			v.diff7 = v.diff7 || 0
			v.diff15 = v.diff15 || 0
		})
		this.ctx.body = sendStat(this.constant.NORMAL, res)
		//{dataList,allUser,authUser,dayInvite}
	}


	async countByRegDay() {
		let query = this.ctx.query
		this.ctx.validate({aid: "pintstr", channelId: "pintstr", date: "date"}, query)
		let queryObj = ObjBase.objFetchKeys(query, ["aid", "channelId", "date"])
		let dateInvite1 = await this.service.count.getDayInvite(queryObj)
		dateInvite1 = dateInvite1.filter((v) => {
			return v && v.dateList
		})
		let dateInvite1Map = ObjBase.arrMapKey(dateInvite1, "dateList")
		let dayAdClick = ObjBase.arrMapKey(await this.service.count.getDayAdClick(queryObj), "dateList")
		// 联合
		let keys = Array.from(new Set(Object.keys(dateInvite1Map).concat(Object.keys(dayAdClick))))
		keys.sort().reverse()
		let res = keys.map(dateList => {
			let v = {dateList}
			if (dayAdClick[dateList]) {
				v.adClick = dayAdClick[dateList].adClick
			} else {
				v.adClick = 0
			}
			if (dateInvite1Map[dateList]) {
				v.userInvite = dateInvite1Map[dateList].userInvite
			} else {
				v.userInvite = 0
			}
			return v
		})
		// console.log(dateInvite1)
		this.ctx.body = sendStat(this.constant.NORMAL, res)
	}
}
module.exports = ChannelController